package com.ls.config;

import com.ls.shiro.cache.RedisCacheManager;
import com.ls.shiro.realms.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //1.创建shirofilter  负责拦截所有请求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //配置系统受限资源
        //配置公共资源
        Map<String, String> map = new HashMap<>();
        map.put("/user/login","anon");
        map.put("/user/register","anon");
        map.put("/register.jsp","anon");
        map.put("/**","authc");
        //默认认证界面路径
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }

    //2.创建安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager( Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        defaultWebSecurityManager.setRealm(realm);

        return defaultWebSecurityManager;
    }

    //3.创建自定义realm
    @Bean
    public Realm getRealm(){
        CustomerRealm realm = new CustomerRealm();
        //修改凭证校验匹配器
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //设置加密算法
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(1024);

        realm.setCredentialsMatcher(hashedCredentialsMatcher);

        /*
        //开启缓存管理
        realm.setCacheManager(new EhCacheManager());
        //设置开启全局缓存
        realm.setCachingEnabled(true);
        realm.setAuthenticationCachingEnabled(true);//开启认证缓存
        realm.setAuthenticationCacheName("authenticationCache");//起名字
        realm.setAuthorizationCachingEnabled(true);//开启授权缓存
        realm.setAuthorizationCacheName("authorizationCache");
        */

        //开启缓存管理
//        realm.setCacheManager(new RedisCacheManager());
//        //设置开启全局缓存
//        realm.setCachingEnabled(true);
//        realm.setAuthenticationCachingEnabled(true);//开启认证缓存
//        realm.setAuthenticationCacheName("authenticationCache");//起名字
//        realm.setAuthorizationCachingEnabled(true);//开启授权缓存
//        realm.setAuthorizationCacheName("authorizationCache");

        return  realm;
    }
}
